package ufrgs.ia.tetralath.models;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;

import ufrgs.ia.tetralath.Tetralath.PLAYER;

public class GamePiece extends JButton {

	/**
	 * Same as main window - i think this should be done because this class <br>
	 * extends a serializable class
	 */
	private static final long serialVersionUID = -231833629085298139L;
	private Dimension pieceDimension;
	
	private Point piecePosition;
	
	private PLAYER cellOwner = PLAYER.NO_ONE;
	
	/**
	 * Initializes the button with an icon and a click listener
	 * @param actionListener - listener that will handle clicks in this cell
	 * @param icon - icon displayed for this piece
	 */
	public GamePiece(ActionListener _actionListener, int _piecePositionX, int _piecePositionY) {
		super();
		
		piecePosition = new Point(_piecePositionX, _piecePositionY);
		pieceDimension = new Dimension(40, 40);
		addActionListener(_actionListener);
		setToolTipText("Me cliiiica caaaaara");
	}
	
	
	public void setClicked(PLAYER _cellOwner, int[][] _gameboard) {

		
		try {
			
			BufferedImage image = null;
			ImageIcon icon; 
			
			switch(_cellOwner) {
				case HUMAN:
					image = ImageIO.read(new File("images/blue_piece_25x25.bmp"));
					break;
				case MINIMAX:
					image = ImageIO.read(new File("images/red_piece_25x25.bmp"));
					break;
				default:
					break;
			}
			
			_gameboard[piecePosition.x][piecePosition.y] = _cellOwner.getValue();
			setToolTipText("Owner: " + _cellOwner.getValue() + " - Position: " + "(" + piecePosition.x + ", " + piecePosition.y + ")");
			
			icon = new ImageIcon(image);
			setIcon(icon);
			
			cellOwner = _cellOwner;
			
		} catch (Exception e) {
			System.out.println("Error in GamePiece.setClicked - trying to change the icon of the piece");
			if(e.getMessage() != null)
				System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}
	
	/**
	 * Gets the owner of the cell
	 * @return cell owner
	 */
	public PLAYER getOwner() {
		return cellOwner;
	}
	
	public boolean hasOwner() {
		return cellOwner != PLAYER.NO_ONE;
	}
	
	/**
	 * Retrieves the position of this cell in the gameboard
	 * @return the position in the gameboard
	 */
	public Point getPiecePosition() {
		return piecePosition;
	}
	
	@Override
	public Dimension getPreferredSize() {
		return pieceDimension;
	}
}
